package cn.aezo.chat_gpt.modules.chat;

import cn.aezo.chat_gpt.config.XfYunConfig;
import cn.aezo.chat_gpt.modules.chat.websocket.WebSocketServer;
import cn.aezo.chat_gpt.modules.chat.websocket.XfYunAiWebsoketListener;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.Message;
import com.unfbx.chatgpt.exception.BaseException;
import com.unfbx.chatgpt.exception.CommonError;
import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.websocket.Session;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class XfYunAiStreamClient {
    private static final Logger log = LoggerFactory.getLogger(OpenAiStreamClient.class);
    private OkHttpClient okHttpClient;
    private @NotNull String hostUrl;
    private String appId;
    private String apiSecret;
    private String apiKey;
    private long connectTimeout;
    private long writeTimeout;
    private long readTimeout;
    private Proxy proxy;

    public XfYunAiStreamClient() {
        this.okHttpClient(30L, 30L, 30L, (Proxy) null);
    }


    private XfYunAiStreamClient(XfYunAiStreamClient.Builder builder) {

        if (StrUtil.isBlank(builder.apiKey)) {
            throw new BaseException(CommonError.API_KEYS_NOT_NUL);
        } else {
            this.hostUrl = builder.hostUrl;
            this.apiKey = builder.apiKey;
            this.apiSecret = builder.apiSecret;
            this.appId = builder.appId;
            this.connectTimeout = builder.connectTimeout;
            this.writeTimeout = builder.writeTimeout;
            this.readTimeout = builder.readTimeout;
            this.okHttpClient(this.connectTimeout, this.writeTimeout, this.readTimeout, this.proxy);
        }
    }


    private void okHttpClient(long connectTimeout, long writeTimeout, long readTimeout, Proxy proxy) {
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.connectTimeout(connectTimeout, TimeUnit.SECONDS);
        client.writeTimeout(writeTimeout, TimeUnit.SECONDS);
        client.readTimeout(readTimeout, TimeUnit.SECONDS);
        if (Objects.nonNull(proxy)) {
            client.proxy(proxy);
        }

        this.okHttpClient = client.build();
    }

    public void streamChatCompletion(String msg,String uid, ConcurrentHashMap<String, Session> webSocketMap) throws Exception {
        try {
            String authUrl = getAuthUrl(this.hostUrl, this.apiKey, this.apiSecret);
            OkHttpClient client = new OkHttpClient.Builder().build();
            String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
            Request request = new Request.Builder().url(url).build();
            client.newWebSocket(request, new XfYunAiWebsoketListener(msg,this.appId,uid,webSocketMap));

        } catch (Exception var9) {
            log.error("请求参数解析异常：{}", var9);
            var9.printStackTrace();
        }
    }

    public static XfYunAiStreamClient.Builder builder() {
        return new XfYunAiStreamClient.Builder();
    }

    public static final class Builder {
        private @NotNull String hostUrl;
        private String appId;
        private String apiSecret;
        private String apiKey;
        private long connectTimeout;
        private long writeTimeout;
        private long readTimeout;

        public Builder() {
        }

        public XfYunAiStreamClient.Builder hostUrl(String val) {
            this.hostUrl = val;
            return this;
        }

        public XfYunAiStreamClient.Builder appId(String val) {
            this.appId = val;
            return this;
        }

        public XfYunAiStreamClient.Builder apiSecret(String val) {
            this.apiSecret = val;
            return this;
        }

        public XfYunAiStreamClient.Builder apiKey(String val) {
            this.apiKey = val;
            return this;
        }

        public XfYunAiStreamClient.Builder connectTimeout(long val) {
            this.connectTimeout = val;
            return this;
        }

        public XfYunAiStreamClient.Builder writeTimeout(long val) {
            this.writeTimeout = val;
            return this;
        }

        public XfYunAiStreamClient.Builder readTimeout(long val) {
            this.readTimeout = val;
            return this;
        }

        public XfYunAiStreamClient build() {
            return new XfYunAiStreamClient(this);
        }
    }

    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }
}
